import './uni.scss';
import { createSSRApp } from 'vue';
import App from './App.vue';
import { setupStore } from '@/store';
import { useNetworkStoreWithOut } from '@/store/modules/network';
import { useUserStoreWithOut } from '@/store/modules/user';
import useHelperStore from '@/utils/helper';
import { setupI18n } from '@/locales/setupI18n';
import router from './router';
import { routesConfig } from './config/routes.config';
import { http } from '@/utils/request';
import uviewPlus from 'uview-plus';
import './mock';
import myTabbar from '@/components/tabbar/index.vue';

const useNetworkStore: any = useNetworkStoreWithOut();

const userStore: any = useUserStoreWithOut();
const useHelperStores: any = new useHelperStore();
const defHttp: any = http;
// 网络状态监听
uni.getNetworkType({
  success: (res) => {
    useNetworkStore.setNetworkState(res.networkType);
  },
});
uni.onNetworkStatusChange(function (res) {
  useNetworkStore.setNetworkState(res.networkType);
});

// 路由导航
router.beforeEach((navType, to) => {
  if (to.route === undefined) {
    throw '路由钩子函数中没有找到to对象，路由信息:' + JSON.stringify(to);
  }
  if (to.route === routesConfig.login.path && userStore.hasLogin) {
    uni.reLaunch({
      url: useHelperStores.objParseUrlAndParam(routesConfig.main.path),
    });
    return;
  }
  console.log(11111111);
  // 过滤需要权限的页面
  if (to.route.requiresAuth) {
    if (userStore.hasLogin) {
      // 已经登录
      uni[navType]({
        url: useHelperStores.objParseUrlAndParam(to.route.path, to.query),
      });
    } else {
      console.log(to);
      // 登录成功后的重定向地址和参数
      const query = {
        redirectUrl: to.route.path,
        ...to.query,
      };
      // 没有登录 是否强制登录?
      if (userStore.hasLogin) {
        uni.redirectTo({
          url: useHelperStores.objParseUrlAndParam(routesConfig.login.path, query),
        });
      } else {
        uni.navigateTo({
          url: useHelperStores.objParseUrlAndParam(routesConfig.main.path, query),
        });
      }
    }
  } else {
    uni[navType]({
      url: useHelperStores.objParseUrlAndParam(to.route, to.query),
    });
  }
});

App.mpType = 'app';
export function createApp() {
  const app = createSSRApp(App);
  app.use(uviewPlus);
  app.use(setupStore);
  app.use(setupI18n);
  app.use(defHttp);
  app.component('myTabbar', myTabbar);
  return {
    app,
  };
}
